<template>
  <div>
    <!-- 新增 修改 详情 -->
    <el-dialog width="800px" :title="title" destroy-on-close append-to-body :visible.sync="show" :before-close="cancel">
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        size="small"
        label-width="150px"
        :style="{
          'pointer-events': type == 'detail' ? ' none' : 'auto',
        }"
      >
        <div style="display: flex; gap: 20px">
          <div style="flex: 1">
            <el-form-item :label="$t('卖家名称')" prop="distrName">
              <el-input v-model="form.distrName" />
            </el-form-item>
            <el-form-item label="卖家地址" prop="address">
              <el-input v-model="form.address" />
            </el-form-item>
            <el-form-item label="卖家电话" prop="tel">
              <el-input v-model="form.tel" />
            </el-form-item>
            <el-form-item label="卖家微信" prop="wechat">
              <el-input v-model="form.wechat" />
            </el-form-item>
            <el-form-item label="卖家负责人" prop="responsibleUser">
              <el-input v-model="form.responsibleUser" />
            </el-form-item>
            <el-form-item label="卖家负责人电话" prop="responsibleTel">
              <el-input v-model="form.responsibleTel" />
            </el-form-item>
            <!-- <el-form-item label="卖家手续费" prop="handlingFee">
              <el-input-number
                style="width: 100%"
                v-model="form.handlingFee"
                controls-position="right"
                :min="0"
              ></el-input-number>
            </el-form-item> -->
            <el-form-item label="卖家级别" prop="level">
              <el-select style="width: 100%" v-model="form.level" :placeholder="$t('请选择')">
                <el-option
                  v-for="(item, index) in seller_level_list"
                  :label="item.dictLabel"
                  :value="+item.dictValue"
                  :key="index"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="卖家邮箱" prop="email">
              <el-input v-model="form.email" />
            </el-form-item>
            <el-form-item label="卖家oicq" prop="oicq">
              <el-input v-model="form.oicq" />
            </el-form-item>
            <el-form-item label="密码" prop="password" v-if="type == 'add'">
              <el-input v-model="form.password" />
            </el-form-item>
            <el-form-item label="卖家利润倍率" prop="profitRate">
              <el-input type="number" v-model.number="form.profitRate" />
            </el-form-item>
            <el-form-item label="卖家营业时间" prop="operateTime">
              <el-time-picker
                value-format="HH:mm:ss"
                format="HH:mm:ss"
                style="width: 100%"
                is-range
                v-model="form.operateTime"
              />
            </el-form-item>
            <el-form-item
              v-hasPermi="['distribution:user:pointAutoPay']"
              label="自动积分抵扣:"
              prop="pointAutoPay"
              style="pointer-events: auto"
            >
              <!-- -->
              <el-radio v-model="form.pointAutoPay" :label="1">是</el-radio>
              <el-radio v-model="form.pointAutoPay" :label="0">否</el-radio>
              <el-button v-if="type == 'detail'" type="primary" size="mini" @click="handlePointAutoPay">
                修改
              </el-button>
            </el-form-item>
            <el-form-item :label="$t('备注')" prop="remark">
              <el-input v-model="form.remark" :rows="4" type="textarea" />
            </el-form-item>
          </div>
          <!-- *******************************手续费率******************************* -->
          <div style="flex: 1">
            <el-form-item label="亚马逊手续费率:" prop="amazonHandingFee">
              <el-input type="number" v-model.number="form.amazonHandingFee">
                <template #append>%</template>
              </el-input>
            </el-form-item>
            <el-form-item label="乐天手续费率:" prop="lotteHandingFee">
              <el-input type="number" v-model.number="form.lotteHandingFee">
                <template #append>%</template>
              </el-input>
            </el-form-item>
            <el-form-item label="雅虎拍卖手续费率:" prop="yahooAuctionHandingFee">
              <el-input v-model="form.yahooAuctionHandingFee">
                <template #append>%</template>
              </el-input>
            </el-form-item>
            <el-form-item label="雅虎商城手续费率:" prop="yahooMallHandingFee">
              <el-input type="number" v-model.number="form.yahooMallHandingFee">
                <template #append>%</template>
              </el-input>
            </el-form-item>
            <el-form-item label="煤炉法人手续费率:" prop="mercariHandingFee">
              <el-input type="number" v-model.number="form.mercariHandingFee">
                <template #append>%</template>
              </el-input>
            </el-form-item>
            <el-form-item label="煤炉个人手续费率:" prop="mercariIndividualHandingFee">
              <el-input type="number" v-model.number="form.mercariIndividualHandingFee">
                <template #append>%</template>
              </el-input>
            </el-form-item>
            <el-form-item label="沃尔玛手续费率:" prop="walmartHandingFee">
              <el-input type="number" v-model.number="form.walmartHandingFee">
                <template #append>%</template>
              </el-input>
            </el-form-item>
            <el-form-item label="Qoo10手续费率:" prop="qoo10HandingFee">
              <el-input type="number" v-model.number="form.qoo10HandingFee">
                <template #append>%</template>
              </el-input>
            </el-form-item>
            <el-form-item label="线下取货手续费率:" prop="offlineHandingFee">
              <el-input type="number" v-model.number="form.offlineHandingFee">
                <template #append>%</template>
              </el-input>
            </el-form-item>
            <div style="height: 250px; border: solid 1px gainsboro; border-radius: 4px; padding: 14px 20px">
              <strong>租户有效期</strong>
              <el-form-item style="margin-top: 10px" label-width="114px" label="是否长期有效:" prop="expireType">
                <el-radio v-model="form.expireType" :label="1">是</el-radio>
                <el-radio v-model="form.expireType" :label="0">否</el-radio>
              </el-form-item>
              <div
                v-if="form.expireType == 0"
                style="
                  height: 140px;
                  border: solid 1px gainsboro;
                  border-radius: 4px;
                  margin: 0 14px;
                  padding: 20px;
                  display: flex;
                  align-items: center;
                  justify-content: center;
                  flex-direction: column;
                "
              >
                <div
                  v-if="type == 'detail'"
                  style="display: flex; align-items: center; flex-direction: column; justify-content: center"
                >
                  <div>有效期至：{{ form.expireTime }}</div>

                  <el-button
                    @click="TopUpNow"
                    :disabled="false"
                    type="primary"
                    size="small"
                    style="height: 30px; width: 100px; margin-top: 40px"
                  >
                    去充值</el-button
                  >
                </div>
                <el-form-item v-else label-width="90px" label="有效期至:" prop="expireTime">
                  <el-date-picker
                    :disabled="false"
                    style="width: 140px"
                    v-model="form.expireTime"
                    type="date"
                    value-format="yyyy-MM-dd"
                    format="yyyy-MM-dd"
                    placeholder="选择日期"
                  >
                  </el-date-picker>
                </el-form-item>
              </div>
            </div>
          </div>
        </div>
        <div style="padding: 10px 0">
          <el-form-item label="推荐人:" prop="referrerId">
            <el-select
              @change="handleReferrerId"
              @clear="handleReferrerIdClear"
              clearable
              filterable
              style="width: 100%"
              v-model="form.referrerId"
            >
              <el-option
                :label="item.name || item.distrName"
                :value="item.distrId"
                :key="item.distrId"
                v-for="item in distributorList"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="推荐人上级:">
            <el-select disabled filterable style="width: 100%" v-model="form.referrerSuperId">
              <el-option
                :label="item.name || item.distrName"
                :value="item.distrId"
                :key="item.distrId"
                v-for="item in distributorList"
              />
            </el-select>
          </el-form-item>
          <!-- 推荐人 校验 -->
          <el-form-item label="推荐人:" prop="referrerProportion" v-if="form.referrerId" key="referrerId1">
            <el-input type="number" v-model.number="form.referrerProportion">
              <el-button slot="prepend"> 比例 </el-button>
              <el-button slot="append">%</el-button>
            </el-input>
          </el-form-item>
          <!-- 推荐人 不校验 -->
          <el-form-item label="推荐人:" v-if="!form.referrerId" key="referrerId2">
            <el-input type="number" v-model.number="form.referrerProportion">
              <el-button slot="prepend"> 比例 </el-button>
              <el-button slot="append">%</el-button>
            </el-input>
          </el-form-item>
          <!-- 推荐人上级 校验 -->
          <el-form-item
            label="推荐人上级:"
            v-if="form.referrerSuperId"
            key="referrerSuperId1"
            prop="referrerSuperProportion"
          >
            <el-input :disabled="!form.referrerSuperId" type="number" v-model.number="form.referrerSuperProportion">
              <el-button slot="prepend"> 比例 </el-button>
              <el-button slot="append">%</el-button>
            </el-input>
          </el-form-item>
          <!-- 推荐人上级 不校验 -->
          <el-form-item v-if="!form.referrerSuperId" label="推荐人上级:" key="referrerSuperId2">
            <el-input :disabled="!form.referrerSuperId" type="number" v-model.number="form.referrerSuperProportion">
              <el-button slot="prepend"> 比例 </el-button>
              <el-button slot="append">%</el-button>
            </el-input>
          </el-form-item>
          <el-form-item label="总公司:" prop="headOfficeProportion">
            <el-input type="number" v-model.number="form.headOfficeProportion">
              <el-button slot="prepend"> 比例 </el-button>
              <el-button slot="append">%</el-button>
            </el-input>
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" v-if="type != 'detail'" @click="handleSubmit"> 确 定 </el-button>
        <el-button @click="cancel">关 闭</el-button>
      </div>
    </el-dialog>
    <RechargeDetails :show.sync="TopUpNowPopFlage"></RechargeDetails>
  </div>
</template>

<script>
import RechargeDetails from '@/components/RechargeDetails/index.vue'
import { useDict } from '@/utils/useDict'
import { getDistributorList, getReferrerRegisterDistributor } from '@/api/platform/supplierManage'
import { insertSellerUser, updateSellerUser, updatePointAutoPay } from '@/api/platform/sellerManage'

export default {
  activated() {
    this.$nextTick(() => this.$refs['TableRef']?.doLayout())
  },
  components: { RechargeDetails },
  props: {
    /**
     * formData
     */
    formData: {
      type: Object,
      default: {},
    },
    /**
     * type
     */
    type: {
      type: String,
      default: 'add',
    },
    /**
     * 控制显示隐藏
     */
    show: {
      type: Boolean,
      required: true,
      default: false,
    },
  },
  data() {
    return {
      TopUpNowPopFlage: false, //充值中心
      seller_level_list: [], //等级字典
      distributorList: [],
      form: {
        /**线下取货手续费率 */
        offlineHandingFee: 0,
        autoVerify: 0,
        applyRestrict: 0,
        type: 2,
        referrerProportion: '',
        referrerSuperProportion: '',
        headOfficeProportion: 100,
        /**自动积分抵扣 */
        pointAutoPay: 0,
      },
      // 表单校验
      rules: {
        distrName: [{ required: true, message: '请输入', trigger: 'blur' }],
        address: [{ required: true, message: '请输入', trigger: 'blur' }],
        tel: [{ required: true, message: '请输入', trigger: 'blur' }],
        applyRestrict: [{ required: true, message: '请选择', trigger: 'blur' }],
        autoVerify: [{ required: true, message: '请选择', trigger: 'blur' }],
        responsibleUser: [{ required: true, message: '请输入', trigger: 'blur' }],
        responsibleTel: [{ required: true, message: '请输入', trigger: 'blur' }],
        operateTime: [{ required: true, message: '请输入', trigger: 'blur' }],
        operateStartTime: [{ required: true, message: '请输入', trigger: 'blur' }],
        operateEndTime: [{ required: true, message: '请输入', trigger: 'blur' }],
        expireTime: [{ required: true, message: '请选择', trigger: 'blur' }],
        email: [
          {
            type: 'email',
            required: true,
            message: '请输入正确的邮箱地址',
            trigger: 'blur',
          },
        ],
        password: [{ required: true, message: '请输入', trigger: 'blur' }],
        profitRate: [{ required: true, message: '请输入', trigger: 'blur' }],
        referrerProportion: [
          {
            validator: this.valid,
            required: true,
            trigger: 'blur',
          },
        ],
        referrerSuperProportion: [
          {
            validator: this.valid,
            required: true,
            trigger: 'blur',
          },
        ],
        headOfficeProportion: [
          {
            validator: this.valid,
            required: true,
            trigger: 'blur',
          },
        ],
        // handlingFee: [{ required: true, message: '请输入', trigger: 'blur' }],
        level: [{ required: true, message: '请输入', trigger: 'blur' }],
        type: [{ required: true, message: '请输入', trigger: 'blur' }],
        // remark: [{ required: true, message: '请输入', trigger: 'blur' }],
        amazonHandingFee: [{ message: '请输入', required: true, trigger: 'blur' }],
        lotteHandingFee: [{ message: '请输入', required: true, trigger: 'blur' }],
        yahooAuctionHandingFee: [{ message: '请输入', required: true, trigger: 'blur' }],
        yahooMallHandingFee: [{ message: '请输入', required: true, trigger: 'blur' }],
        mercariHandingFee: [{ message: '请输入', required: true, trigger: 'blur' }],
        mercariIndividualHandingFee: [{ message: '请输入', required: true, trigger: 'blur' }],
        walmartHandingFee: [{ message: '请输入', required: true, trigger: 'blur' }],
        qoo10HandingFee: [{ message: '请输入', required: true, trigger: 'blur' }],
        offlineHandingFee: [{ message: '请输入', required: true, trigger: 'blur' }],
      },
    }
  },
  computed: {
    title() {
      if (this.type == 'add') {
        return this.$t('添加')
      }
      if (this.type == 'edit') {
        return this.$t('编辑')
      }
      if (this.type == 'detail') {
        return this.$t('详情')
      }
    },
  },
  watch: {
    show: function (newValue) {
      if (newValue) {
        /**获取等级字典 */
        this.getTypeList()
        this.resetForm()
        if (this.type == 'add') {
          this.form.distributorList = []
          this.distributorList = []
          getDistributorList().then((res) => {
            const { code, data, msg } = res
            if (code === 200) {
              this.distributorList = res.data
            }
          })
        }
        if (this.type == 'edit' || this.type == 'detail') {
          Object.keys(this.formData).forEach((key) => {
            this.$set(this.form, key, this.formData[key])
          })
          this.form.operateTime = this.form.operateTime?.split('-').map((i) => {
            return i.length == 5 ? i + ':00' : i
          })
          this.distributorList = this.formData.distributorList

          console.log(`this.form ==>`, JSON.parse(JSON.stringify(this.form)))
        }
      }
    },
    TopUpNowPopFlage: function (newValue) {
      // if (!newValue) {
      //   this.cancel()
      // }
    },
  },
  methods: {
    handlePointAutoPay() {
      updatePointAutoPay(this.form).then((res) => {
        const { code, data, msg } = res
        if (code === 200) {
          this.$message({ type: 'success', message: msg })
          this.cancel()
          this.$emit('getList')
        }
      })
    },
    /**去充值 */
    TopUpNow() {
      this.TopUpNowPopFlage = true
    },
    getTypeList() {
      useDict('seller_level').then((res) => {
        this.seller_level_list = res.seller_level
      })
    },
    handleReferrerIdClear() {
      this.form.referrerSuperId = null
      this.form.referrerProportion = null
      this.form.referrerSuperProportion = null
      this.form.headOfficeProportion = 100
    },
    handleReferrerId(distrId) {
      this.form.referrerSuperProportion = null
      if (!distrId) return
      console.log(`distrId ==>`, JSON.parse(JSON.stringify(distrId)))
      getReferrerRegisterDistributor({
        distrId,
      }).then((res) => {
        this.form.referrerSuperId = res.data.distrId
      })
    },
    /**验证推荐人 */
    valid(rule, value, callback) {
      console.log(`rule, value, ==>`, JSON.parse(JSON.stringify({ rule, value })))
      const { field } = rule
      const {
        /** 推荐人*/
        referrerProportion,
        /** 推荐人上级*/
        referrerSuperProportion,
        /** 总公司*/
        headOfficeProportion,
      } = this.form

      if (String(value).trim() == '') {
        return callback(new Error('请输入'))
      }

      if (field == 'referrerProportion' /**推荐人 */) {
        if (+referrerProportion > 100 || +referrerProportion < 0) {
          return callback(new Error('取值范围在0~100'))
        }
      }

      if (field == 'referrerSuperProportion' /**推荐人上级 */) {
        if (+referrerSuperProportion > 100 || +referrerSuperProportion < 0) {
          return callback(new Error('取值范围在0~100'))
        }
      }

      if (field == 'headOfficeProportion' /**总公司 */) {
        if (+headOfficeProportion > 100 || +headOfficeProportion < 0) {
          return callback(new Error('取值范围在0~100'))
        }
      }

      const total = +referrerProportion + +referrerSuperProportion + +headOfficeProportion

      if (total > 100) {
        callback(new Error('总和不能超过100'))
      }
      return callback()
    },

    handleSubmit() {
      // 判断分成相加是否为100
      const {
        /** 推荐人*/
        referrerProportion,
        /** 推荐人上级*/
        referrerSuperProportion,
        /** 总公司*/
        headOfficeProportion,
      } = this.form
      const total = +referrerProportion + +referrerSuperProportion + +headOfficeProportion

      if (total != 100) {
        return this.$message.error('比例总和必须为100')
      }

      this.$refs['formRef'].validate((valid) => {
        if (valid) {
          const data = JSON.parse(JSON.stringify(this.form))
          data.operateTime = data.operateTime?.join('-')
          if (this.type == 'add') {
            insertSellerUser(data).then((res) => {
              const { code, data, msg } = res
              if (code === 200) {
                this.$message({ type: 'success', message: msg })

                this.cancel()
                this.$emit('getList')
              }
            })
          } else {
            updateSellerUser(data).then((res) => {
              const { code, data, msg } = res
              if (code === 200) {
                this.$message({ type: 'success', message: msg })

                this.cancel()
                this.$emit('getList')
              }
            })
          }
        }
      })
    },
    resetForm() {
      Object.keys(this.form).forEach((key) => (this.form[key] = ''))
    },

    cancel() {
      this.$emit('update:show', false)
    },
  },
}
</script>
<style scoped lang="scss"></style>
